<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="活动类型" prop="activityTypeId">
        <el-select
          v-model="queryParams.activityTypeId"
          placeholder="请选择活动类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.activity_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="activityStartTime">
        <el-date-picker
          clearable
          v-model="queryParams.activityStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="结束时间" prop="activityEndTime">
        <el-date-picker
          clearable
          v-model="queryParams.activityEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="发起人" prop="activityInitiator">
        <el-input
          v-model="queryParams.activityInitiator"
          placeholder="请输入发起人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['activity:activities:add']"
          >创建活动</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['activity:activities:edit']"
          >修改活动</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['activity:activities:remove']"
          >撤销活动</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['activity:activities:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="activitiesList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="0" align="center" />
      <el-table-column label="活动ID" align="center" prop="activityId" />
      <el-table-column label="活动标题" align="center" prop="activityTitle" />
      <el-table-column label="活动类型" align="center" prop="activityTypeId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.activity_type"
            :value="scope.row.activityTypeId"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="activityStartTime"
        width="0"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.activityStartTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="activityEndTime"
        width="0"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进行状态" align="center" prop="activityProgress">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.activity_progress"
            :value="scope.row.activityProgress"
          />
        </template>
      </el-table-column>
      <el-table-column label="发起人" align="center" prop="activityInitiator" />
      <el-table-column
        label="发起时间"
        align="center"
        prop="activityInitiationTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.activityInitiationTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核状态"
        align="center"
        prop="activityReviewStatus"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.activity_status"
            :value="scope.row.activityReviewStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['activity:activities:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['activity:activities:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动标题" prop="activityTitle">
          <el-input v-model="form.activityTitle" placeholder="请输入活动标题" />
        </el-form-item>

        <el-form-item label="活动类型" prop="activityTypeId">
          <el-select v-model="form.activityTypeId" placeholder="请选择活动类型">
            <el-option
              v-for="dict in dict.type.activity_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="activityStartTime">
          <el-date-picker
            clearable
            v-model="form.activityStartTime"
            type="datetime"
            format="yyyy年MM月dd  HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            popper-class="no-atTheMoment"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="activityEndTime">
          <el-date-picker
            clearable
            v-model="form.activityEndTime"
            type="datetime"
            format="yyyy年MM月dd  HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            popper-class="no-atTheMoment"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="活动内容">
          <editor v-model="form.activityContent" :min-height="192" />
        </el-form-item>

        <el-form-item label="上级部门" prop="activityScope">
          <treeselect
            v-model="form.activityScope"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="选择上级部门"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--查看活动总结框-->
    <el-dialog
      :title="title"
      :visible.sync="openView"
      width="80%"
      append-to-body
    >
      <div class="activity-layout">
        <div class="summary-area">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="活动标题" prop="activityTitle">
              <el-input
                v-model="form.activityTitle"
                placeholder="请输入活动标题"
              />
            </el-form-item>
            <el-form-item label="活动类型" prop="activityTypeId">
              <el-select
                v-model="form.activityTypeId"
                placeholder="请选择活动类型"
              >
                <el-option
                  v-for="dict in dict.type.activity_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间" prop="activityStartTime">
              <el-date-picker
                clearable
                v-model="form.activityStartTime"
                type="datetime"
                format="yyyy年MM月dd  HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                popper-class="no-atTheMoment"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" prop="activityEndTime">
              <el-date-picker
                clearable
                v-model="form.activityEndTime"
                type="datetime"
                format="yyyy年MM月dd  HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                popper-class="no-atTheMoment"
                placeholder="请选择结束时间"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="活动内容" prop="activityContent">
              <editor v-model="form.activityContent" v-if="openView" />
            </el-form-item>
            <el-form-item label="上级部门" prop="activityScope">
              <treeselect
                v-model="form.activityScope"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="participant-table-area">
          <h2>活动参与人</h2>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd01"
                v-hasPermi="['activity:activities:add']"
                >加入活动</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['system:participants:import']"
                >导入</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport01"
                v-hasPermi="['system:participants:export']"
                >导出</el-button
              >
            </el-col>
          </el-row>
          <el-table
            v-loading="loading"
            :data="activityParticipants"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="0" align="center" />
            <el-table-column
              label="参与人ID"
              align="center"
              prop="activityParticipantId"
            />
            <el-table-column
              label="参与人"
              align="center"
              prop="activityParticipant"
            />
            <el-table-column
              label="参与时间"
              align="center"
              prop="activityParticipantTime"
              width="0"
            >
            </el-table-column>
            <el-table-column
              label="更新者ID"
              align="center"
              prop="updateById"
              width="0"
            >
              <template slot-scope="scope">
                {{ scope.row.updateById }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作类型"
              align="center"
              prop="oper"
              width="0"
            >
              <template slot-scope="scope">
                <!-- 根据操作类型显示不同的文本 -->
                <span v-if="scope.row.oper === 0">退出活动</span>
                <span v-if="scope.row.oper === 1">加入活动</span>
                <span v-if="scope.row.oper === 2">暂未参与</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete01(scope.row)"
                  v-hasPermi="['activity:activities:view']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listActivities,
  getActivities,
  delActivities,
  addActivities,
  updateActivities,
  addactivityParticipant,
  delactivityParticipant,
} from "@/api/activity/activities";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import { listDept } from "@/api/system/dept";
import { getDept } from "@/api/system/dept";

export default {
  name: "Activities",
  dicts: ["activity_status", "activity_type", "activity_progress"],
  components: { Treeselect },
  data() {
    return {
      isFormDisabled: true, // 初始化为true，表示表单被禁用
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      deptOptions: [],
      // 部门名称
      deptName: null,
      // 参与人列表表格数据
      activityParticipants: [],
      // 活动列表表格数据
      activitiesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      //点击活动的ID
      aID: 0,
      // 发起人ID时间范围
      daterangeActivityInitiationTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: null,
        activityContent: "",
        activityTitle: null,
        activityTypeId: null,
        activityStartTime: null,
        activityEndTime: null,
        activityInitiator: null,
        activityInitiatorId: null,
        activityReviewStatus: null,
      },
      // 表单活动参数
      form: {
        deptId: null,
        activityParticipant: "",
        activityParticipantId: "",
        activityParticipantTime: "",
        activityScope: "",
        // activityParticipant: "",
        // activityParticipantId: "",
        // activityParticipantTime: "",
        oper: "",
        deptName: null,
      },

      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        activityTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        activityContent: [
          { required: true, message: "活动内容不能为空", trigger: "blur" },
        ],
        activityTypeId: [
          { required: true, message: "活动类型不能为空", trigger: "change" },
        ],
        activityStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        activityEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/activity/activities/importData",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    isOwner(activity) {
      // 检查当前用户是否是活动的创建者
      return activity.creatorId === this.currentUser.id;
    },
    /** 查询活动列表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (
        null != this.daterangeActivityInitiationTime &&
        "" != this.daterangeActivityInitiationTime
      ) {
        this.queryParams.params["beginActivityInitiationTime"] =
          this.daterangeActivityInitiationTime[0];
        this.queryParams.params["endActivityInitiationTime"] =
          this.daterangeActivityInitiationTime[1];
      }
      listActivities(this.queryParams).then((response) => {
        this.activitiesList = response.rows;
        console.log(this.activitiesList);
        this.total = response.total;
        this.loading = false;
      });

      // addactivityParticipant(this.queryParams).then((response) => {
      //   this.activityParticipants = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityTitle: null,
        activityContent: null,
        activityTypeId: null,
        activityStartTime: null,
        activityEndTime: null,
        activityProgress: null,
        activityInitiator: null,
        activityInitiatorId: null,
        activityInitiationTime: null,
        activityUpdateTime: null,
        activityReviewer: null,
        activityReviewTime: null,
        activityReviewComment: null,
        activityReviewStatus: null,
        activityScope: " ",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeActivityInitiationTime = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.activityId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "activity/participants/importTemplate",
        {},
        `template_${new Date().getTime()}.xlsx`
      );
    },
    /** 新增按钮操作 */
    /*添加参与人操作 */
    handleAdd01() {
      const activityId = this.form.activityId || this.ids[0];

      this.$modal
        .confirm(`是否加入活动编号为 "${activityId}" 的数据项？`)
        .then(() => {
          return addactivityParticipant(activityId);
        })
        .then(() => {
          // 假设getList方法返回包含了activityParticipants的Promise
          return this.getList();
        })
        .then((response) => {
          // 确保getList返回的数据结构中activityParticipants存在并正确
          if (
            response.data &&
            Array.isArray(response.data.activityParticipants)
          ) {
            this.activityParticipants = response.data.activityParticipants;
          } else {
            console.error(
              "getList返回的数据结构不正确，无法获取activityParticipants"
            );
          }
          this.$modal.msgSuccess("添加成功");
        });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动列表";

      const deptId = this.currentDeptid;
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
      console.log("bumen", deptId);
    },
    /** 任务详细信息 */
    handleView(row) {
      getActivities(row.activityId).then((response) => {
        this.form = response.data;
        this.openView = true;
        this.title = "活动总结";
        const deptId = response.data.activityScope;
        const activityData = response.data;
        console.log("部门列", this.form.activityScope);
        getDept(deptId).then((deptResponse) => {
          const idName = deptResponse.data.deptName;
          console.log("活动名", idName);

          // 合并部门数据到活动数据
          activityData.activityScope = idName;

          // 将合并后的数据赋值给 this.form
          this.form = activityData;
        });
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityId || this.ids;
      getActivities(activityId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动列表";
      });
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.activityId != null) {
            updateActivities(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivities(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    /*删除按钮操作 */
    /*删除活动参与人操作 */
    handleDelete01(row) {
      const activityId = row.activityId;
      const activityParticipantId = row.activityParticipantId;
      const requestData = [{ activityId, activityParticipantId }];

      this.$modal
        .confirm(
          `是否确认删除活动ID为 "${activityId}" 的参与人编号为 "${activityParticipantId}" 的数据项？`
        )
        .then(() => {
          return delactivityParticipant(requestData);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /*删除列表活动 */
    handleDelete(row) {
      const activityIds = row.activityId || this.ids;

      this.$modal
        .confirm('是否确认删除活动列表编号为"' + activityIds + '"的数据项？')
        .then(function () {
          return delActivities(activityIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "activity/activities/export",
        {
          ...this.queryParams,
        },
        `activities_${new Date().getTime()}.xlsx`
      );
    },
    handleExport01() {
      this.download(
        "activity/activities/export",
        {
          activityId: this.queryParams.activityId, // 只导出activityId参数
        },
        `activities_${new Date().getTime()}.xlsx`
      );
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "活动参与人导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
  watch: {},
};
</script>
<style scoped>
.activity-layout {
  display: flex;
  justify-content: space-between;
}

.summary-area,
.participant-table-area {
  width: 48%; /* 根据实际情况调整 */
}
.summary-area.disabled {
  pointer-events: none;
  opacity: 0.6;
}

/* 表格和表单的其他样式可以在这里继续添加 */
</style>
